package vn.edu.uit.wifi_transfering;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class Transferation extends Activity implements View.OnTouchListener {

	private DragController mDragController; // Object that sends out drag-drop
	// events while a view is being
	// moved.
	private DragLayer mDragLayer; // The ViewGroup that supports drag-drop.
	private boolean mLongClickStartsDrag = false; // If true, it takes a long
	// click to start the drag
	// operation.
	// Otherwise, any touch
	// event starts a drag.

	private GridView gridView;
	private static final int CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST;

	public static final boolean Debugging = false;

	private ImageButton ibBack;
	private ImageButton ibUp;

	ArrayAdapter<String> adapter;
	 
	public static final String ACTION_WIDGET = "vn.edu.uit.wifi_transfering.Transferation.ACTION_WIDGET";
	private static final String PREFS_NAME = "ManagerPrefsFile"; // user
																	// preference
																	// file name
	private static final String PREFS_HIDDEN = "hidden";
	private static final String PREFS_COLOR = "color";
	private static final String PREFS_THUMBNAIL = "thumbnail";
	private static final String PREFS_SORT = "sort";

	private FileManager mFileMag;
	private EventHandler mHandler;
	private EventHandler.TableRow mTable;

	private SharedPreferences mSettings;
	private TextView mPathLabel, mDetailLabel, mStorageLabel;

	/**
	 * onCreate - called when the activity is first created.
	 * 
	 * Creates a drag controller and sets up three views so click and long click
	 * on the views are sent to this activity. The onLongClick method starts a
	 * drag sequence.
	 * 
	 */

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		mDragController = new DragController(this);

		setContentView(R.layout.transfer_layout);
				
		

		/* read settings */
		mSettings = getSharedPreferences(PREFS_NAME, 0);
		boolean hide = mSettings.getBoolean(PREFS_HIDDEN, false);
		boolean thumb = mSettings.getBoolean(PREFS_THUMBNAIL, true);
		int color = mSettings.getInt(PREFS_COLOR, -1);
		int sort = mSettings.getInt(PREFS_SORT, 3);

		mFileMag = new FileManager();
		mFileMag.setShowHiddenFiles(hide); // khoi tao ban dau la ko an
		mFileMag.setSortType(sort); // khoi tao ban dau la sap xep tang dan theo
									// dung luong

		if (savedInstanceState != null)
			mHandler = new EventHandler(Transferation.this, mFileMag,
					savedInstanceState.getString("location"));
		else
			mHandler = new EventHandler(Transferation.this, mFileMag); // tai
																		// day
																		// khoi
		// tao duong dan
		// den thu muc
		// hien tai de
		// lay danh sach

		mHandler.setTextColor(color);
		mHandler.setShowThumbnails(thumb); // khoi tao ban dau la tao thumbnail
		mTable = mHandler.new TableRow(); // tao mot danh sach theo duong dan
											// khoi tao ban sau

		ibBack = (ImageButton) findViewById(R.id.back_button);
		ibBack.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent instentTransfer = new Intent(Transferation.this, MainActivity.class);								
				startActivity(instentTransfer);
				finish();
			}
		});
		ibUp = (ImageButton) findViewById(R.id.up_button);
		ibUp.setOnClickListener(mHandler);

		mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
		mDragLayer.setDragController(mDragController);
		mDragController.addDropTarget(mDragLayer);

		gridView = (GridView) findViewById(R.id.gridview);

		gridView.setOnItemClickListener(listClickedItem);
		mHandler.setListAdapter(mTable);
		gridView.setAdapter(mTable);

		// gridView.setAdapter(new ImageAdapter(this));

		String message = mLongClickStartsDrag ? "Press and hold to start dragging."
				: "Touch a view to start dragging.";
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
				.show();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString("location", mFileMag.getCurrentDir());
	}

	public OnItemClickListener listClickedItem = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			// TODO Auto-generated method stub
			final String item = mHandler.getData(position);
			File file = new File(mFileMag.getCurrentDir() + "/" + item);
			String item_ext = null;

			try {
				item_ext = item.substring(item.lastIndexOf("."), item.length());

			} catch (IndexOutOfBoundsException e) {
				item_ext = "";
			}

			if (file.isDirectory()) {
				if (file.canRead()) {
					mHandler.stopThumbnailThread();
					// item = sdcard
					mHandler.updateDirectory(mFileMag.getNextDir(item, false));
					// mPathLabel.setText(mFileMag.getCurrentDir());

					/*
					 * set back button switch to true (this will be better
					 * implemented later)
					 */
					// if (!mUseBackKey)
					// mUseBackKey = true;

				} else {
					Toast.makeText(Transferation.this,
							"Can't read folder due to permissions",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	/**
	 * Build a menu for the activity.
	 * 
	 */

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, CHANGE_TOUCH_MODE_MENU_ID, 0, "Change Touch Mode");
		return true;
	}

	/**
	 * Handle a click on a view. Tell the user to use a long click (press).
	 * 
	 */

	// public void onClick(View v) {
	// // if (mLongClickStartsDrag) {
	// // // Tell the user that it takes a long click to start dragging.
	// // toast("Press and hold to drag an image.");
	// // }
	// String content = (String) v.getContentDescription();
	// if (content.equals("Folder")) {
	// Toast.makeText(getBaseContext(), content, Toast.LENGTH_SHORT).show();
	// return;
	// } else {
	// Toast.makeText(getBaseContext(), "File", Toast.LENGTH_SHORT).show();
	// }
	// }

	/**
	 * Handle a long click. If mLongClick only is true, this will be the only
	 * way to start a drag operation.
	 * 
	 * @param v
	 *            View
	 * @return boolean - true indicates that the event was handled
	 */

	// public boolean onLongClick(View v) {
	// if (mLongClickStartsDrag) {
	//
	// // trace ("onLongClick in view: " + v + " touchMode: " +
	// // v.isInTouchMode ());
	//
	// // Make sure the drag was started by a long press as opposed to a
	// // long click.
	// // (Note: I got this from the Workspace object in the Android
	// // Launcher code.
	// // I think it is here to ensure that the device is still in touch
	// // mode as we start the drag operation.)
	// if (!v.isInTouchMode()) {
	// toast("isInTouchMode returned false. Try touching the view again.");
	// return false;
	// }
	// return startDrag(v);
	// }
	//
	// // If we get here, return false to indicate that we have not taken care
	// // of the event.
	// return false;
	// }

	/**
	 * Perform an action in response to a menu item being clicked.
	 * 
	 */

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CHANGE_TOUCH_MODE_MENU_ID:
			mLongClickStartsDrag = !mLongClickStartsDrag;
			String message = mLongClickStartsDrag ? "Changed touch mode. Drag now starts on long touch (click)."
					: "Changed touch mode. Drag now starts on touch (click).";
			Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
					.show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * This is the starting point for a drag operation if mLongClickStartsDrag
	 * is false. It looks for the down event that gets generated when a user
	 * touches the screen. Only that initiates the drag-drop sequence.
	 * 
	 */

	public boolean onTouch(View v, MotionEvent ev) {
		// If we are configured to start only on a long click, we are not going
		// to handle any events here.
		// if (mLongClickStartsDrag)
		// return false;

		String content = (String) v.getContentDescription();
		if (content.equals("Folder")) {
			// Toast.makeText(getBaseContext(), content,
			// Toast.LENGTH_SHORT).show();
			return false;
		}

		boolean handledHere = false;

		final int action = ev.getAction();

		// In the situation where a long click is not needed to initiate a drag,
		// simply start on the down event.
		if (action == MotionEvent.ACTION_DOWN) {
			handledHere = startDrag(v);
		}

		return handledHere;
	}

	/**
	 * Start dragging a view.
	 * 
	 */

	public boolean startDrag(View v) {
		// Let the DragController initiate a drag-drop sequence.
		// I use the dragInfo to pass along the object being dragged.
		// I'm not sure how the Launcher designers do this.
		Object dragInfo = v;
		mDragController.startDrag(v, mDragLayer, dragInfo,
				DragController.DRAG_ACTION_MOVE);
		return true;
	}

	/**
	 * Finds all the views we need and configure them to send click events to
	 * the activity.
	 * 
	 */
	// private void setupViews() {
	// DragController dragController = mDragController;
	//
	// mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
	// mDragLayer.setDragController(dragController);
	// dragController.addDropTarget(mDragLayer);
	//
	// gridView = (GridView) findViewById(R.id.gridview);
	// gridView.setAdapter(new ImageAdapter(this));
	//
	// String message = mLongClickStartsDrag ?
	// "Press and hold to start dragging."
	// : "Touch a view to start dragging.";
	// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
	// .show();
	//
	// }

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg
	 *            String
	 * @return void
	 */

	public void toast(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	} // end toast

	/**
	 * Send a message to the debug log and display it using Toast.
	 */

	public void trace(String msg) {
		if (!Debugging)
			return;
		Log.d("DragActivity", msg);
		toast(msg);
	}

	private void changeDirectory() {

	}

}
